package data.join.com.media;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.text.TextUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import data.join.com.application.EventMessage;
import data.join.com.database.bean.FileNameSync;
import data.join.com.database.bean.FileNameSyncPref;
import data.join.com.database.bean.FileUploadPref;
import data.join.com.database.bean.ImageBean;
import data.join.com.database.bean.ImageDBPref;
import data.join.com.database.bean.VideoBean;
import data.join.com.database.bean.VideoDBPref;
import data.join.com.http.HttpServer;
import data.join.com.media.VideoModule.VideoModule;
import data.join.com.media.VideoModule.VideoModuleBuild;
import data.join.com.utils.BaseThread;
import data.join.com.utils.ImageUtils;
import data.join.com.utils.MyLog;
import data.join.com.utils.NativeImageLoader;
import data.join.com.utils.VideoUtils;
import data.join.com.utils.WakeLockUtils;


/**
 * Created by wenlong on 16-4-18.
 */
public class VideoScannerThread extends BaseThread {
    private static final int VIDEO_DURATION = 10*1000;

    private String TAG = "VideoScannerThread";
    public String mVideoDirPath = "/storage/sdcard1/DVR";

    private static VideoScannerThread mInstance;

    private Context mContext;
    private VideoModule mVideoLock;

    private VideoScannerThread(Context context) {
        mContext = context;
        mVideoLock = new VideoModuleBuild(mContext).build();
    }

    public static VideoScannerThread getInstance(Context context){
        if(mInstance == null){
            mInstance = new VideoScannerThread(context);
        }
        return mInstance;
    }

    @Override
    public void run() {
        clearNotExistFile();
    }

    private void clearNotExistFile() {
        synchronized (this) {
            MyLog.D(TAG, "clearNotExistFile");
            VideoDBPref.getInstance().clearNotExistFile();
        }
    }

    public void addVideoFile(String filePath){
        synchronized (this) {
            scanVideoFile(filePath);
        }
    }

    public void removeVideoFile(String filePath){
        synchronized (this) {
            VideoDBPref.getInstance().deleteVideoByPath(filePath);
        }
    }

    public void scanVideoFile(String filePath){
        File f = new File(filePath);

        if (isVideoFile(f.getName()) && !VideoDBPref.getInstance().existVideoByPath(f.getAbsolutePath())) {

            VideoBean video = getVideoInfo(mContext, f);

            if (video != null) {

                checkVideoLocked(video);

                if (video.videoType == VideoModule.VIDEO_TYPE_LOCK) {
                    saveLockVideo(video);

                    if(video.id != null) {
                        FileUploadPref.getInstance().insertFileUploadById(video.id, FileUploadPref.UPLOAD_TYPE_VIDEO);
                        MyLog.D(TAG, "this is lock video,insertFileUploadById");
                    }
                }else{
                    saveVideo(video);
                }

            } else {
                MyLog.D(TAG, "video is null " + f.getPath());
            }
        }
    }

    private VideoBean getVideoInfo(Context c, File f){
        VideoBean video = null;

        if(f.exists()) {
            video = VideoUtils.getVideoInfoByPath(f);
        }else{
            MyLog.D("video file not exist"+f.getName());
        }

        return video;
    }

    private void checkVideoLocked(VideoBean video){
        if(mVideoLock!= null){
            video.startTime = mVideoLock.getVideoStartTime(video);
            video.videoType = mVideoLock.getVideoType(video);
            video.backOrFont = mVideoLock.getVideoBackOrFront(video);
            video.endTime = mVideoLock.getVideoEndTime(video);
        }
    }

    private void saveVideo(VideoBean video){
        if(video.duration > VIDEO_DURATION) {
            long start = video.startTime;
            long end = video.endTime;

            long offset = start;
            long duration;

            while(true){

                if(offset < end){

                    if(offset + VIDEO_DURATION + 4000 < end) {
                        duration = VIDEO_DURATION;
                    }else{
                        duration = end - offset;
                    }
                    //MyLog.D(TAG,"start="+(offset-start)+",duration="+duration+",end="+(end-start));
                }else{
                    break;
                }

                VideoBean videoBean = copyVideoBean(video);

                videoBean.startTime = offset;
                videoBean.duration = duration;
                videoBean.endTime = videoBean.startTime + videoBean.duration;

                VideoDBPref.getInstance().insertVideoBean(videoBean);

                FileNameSyncPref.getInstance().insertFileNameSync(videoBean, FileNameSyncPref.FILE_SYNC_ACTION_ADD);

                offset = offset + duration;

                //MyLog.D(TAG,"insert video "+videoBean.duration+"ms,"+videoBean.srcPath);
            }
        }else if(video.duration > 0){

            VideoDBPref.getInstance().insertVideoBean(video);

            FileNameSyncPref.getInstance().insertFileNameSync(video, FileNameSyncPref.FILE_SYNC_ACTION_ADD);
        }else{
            MyLog.E(TAG,"saveVideo error");
        }
        MyLog.D(TAG,"saveVideo complete, video.duration ="+video.duration+",path="+video.srcPath);
    }

    private void saveLockVideo(VideoBean video){
        if(video.duration > 0){
            VideoDBPref.getInstance().insertVideoBean(video);
            MyLog.D(TAG,"saveLockVideo complete, video.duration ="+video.duration+",path="+video.srcPath);
        }else{
            MyLog.E(TAG,"saveLockVideo error");
        }
    }

    private VideoBean copyVideoBean(VideoBean video){
        VideoBean videoBean = new VideoBean();
        videoBean.duration = video.duration;
        videoBean.srcPath = video.srcPath;
        videoBean.thumbnail = video.thumbnail;
        videoBean.startTime = video.startTime;
        videoBean.endTime = video.endTime;
        videoBean.videoType = video.videoType;
        videoBean.backOrFont = video.backOrFont;
        return videoBean;
    }

    private boolean isVideoFile(String filename) {
        boolean ret = false;
        String temp = filename.toLowerCase();
        if (temp.endsWith(".ts") || temp.endsWith(".mp4") || temp.endsWith(".mov") || temp.endsWith(".3gp")) {
            ret = true;
        }
        return ret;
    }

}
